var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
var fs = require('fs');

// 读取历史信息
function readData() {
  try {
    var data = fs.readFileSync('./data.json', 'utf-8');
    data = JSON.parse(data);
    return data;
  } catch (error) {
    return null;
  }
}

// 写入信息
function writeData(msg, data) {
  try {
    data['data'].push(msg);
    data = JSON.stringify(data);
    fs.writeFileSync('./data.json', data);
    return true
  } catch (error) {
    return false;
  }
  
}


app.use('/public/', express.static('./public'));

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
  for (let index = 0; index < readData()['data'].length; index++) {
    var msg = readData()['data'][index];
    console.log("向客户端发送: ", msg)
    socket.emit('chat', msg)  
  }
  socket.on('chat', function(msg){
    if (writeData(msg, readData())) {
      io.emit('chat', msg);
      console.log("向服务端发送: ", msg);
    }
  });
});
  
http.listen(port, function(){
  console.log('listening on *:' + port);
});
